package cn.com.w.web.Handler;

import cn.com.w.common.Emun.Register;
import cn.com.w.common.PO.LoginRequest;
import cn.com.w.common.Utils.JedisUtils;
import cn.com.w.common.VO.BaseVO;
import cn.com.w.dao.Entity.SysUser;
import cn.com.w.secutity.Security.JwtTokenUtils;
import cn.com.w.web.Factory.RegisterJudgeFactory;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author w
 * @Description:
 * @DateTime: 2025 05 07 11:56
 **/
@Component
public class AuthHandler {

    private final UserHandler userHandler;

    private final JwtTokenUtils jwtTokenUtils;

    private final RegisterJudgeFactory registerJudgeFactory;

    @Autowired
    public AuthHandler(UserHandler userHandler
            , JwtTokenUtils jwtTokenUtils
            , RegisterJudgeFactory registerJudgeFactory) {
        this.userHandler = userHandler;
        this.jwtTokenUtils = jwtTokenUtils;
        this.registerJudgeFactory = registerJudgeFactory;
    }

    public String blackKey = "blackListToken";


    public BaseVO<?> login(LoginRequest loginRequest) throws Exception {
        String token = null;
        if (StringUtils.isEmpty(loginRequest.getUsername())){
            BaseVO.error("请输入登录人！");
        }
        if (userHandler.checkPassword(loginRequest.getUsername(), loginRequest.getPassWord())) {
            token = userHandler.generalToken(loginRequest.getUsername());
        } else {
            BaseVO.error("密码错误！");
        }
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        return BaseVO.builder().content(map).build();
    }

    public BaseVO<?> logOut(String token) throws Exception {
        if (StringUtils.isEmpty(token)) {
            return BaseVO.builder().code(0).message("请填写token").build();
        }
        String jwt = token.replace("Bearer ", "");
        long remainingSeconds = jwtTokenUtils.getExpiredDateFromToken(jwt)
                .getTime() - System.currentTimeMillis();

        // 将Token加入黑名单（有效期为剩余时间）
        JedisUtils.setWithExpire(blackKey, jwt, remainingSeconds);
        return BaseVO.builder().code(200).message("登出成功").build();
    }

    public BaseVO<?> register(String username, String password, String other, Register type) throws Exception {
        //名称、手机号、邮箱、wechat 重复判断，有效性判断
        registerJudgeFactory.registerJudge(type).check(other);
        //用户名检查
        checkUserName(username);
        return userHandler.saveOne(username, password, other, type);
    }

    private void checkUserName(String username) throws Exception {
        LambdaQueryWrapper<SysUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SysUser::getUsername, username);
        if (userHandler.userService.count(wrapper) > 0) {
            BaseVO.error("该用户名已经注册，请更换用户名！");
        }
    }
}